import CCNodePool from "./CCNodePool";
import ResItem from "../res/ResItem";
import SelfPool from "./SelfPool";

export default class PoolManager {

    private static ins:PoolManager;

    static instance():PoolManager{
        if(!this.ins){
            this.ins = new PoolManager();
        }
        return this.ins;
    }

 
    //对象池表
    private pools = {};
    // 对象名称 和给定 key的 映射表
    private nameMap = {};


    init(key:string,resItem:ResItem,count:number){
       
        if(!this.pools[key]){
            cc.log(' PoolManger init ',key,count)
            this.pools[key] = new SelfPool(new CCNodePool(key,resItem, count)) 
        }
       
    }


    getPool(key:string){
        return this.pools[key].getPool();
    }

    get(key: string): cc.Node {
        
        if(this.pools[key]){
            // cc.log("getNode --------------------------- 对象池剩余对象数量  ",key,this.pools[key].size());
            let go: cc.Node = this.pools[key].get();
            if (!this.nameMap[go.name] && go.name != key) {
                this.nameMap[go.name] = key;
            }
            return go;
        }
        return null;
    }


    put(go: cc.Node,nodePool:boolean = false) {

        let key = this.nameMap[go.name];

        if (!key) {
            key = go.name;
        }

        if (!this.pools[key]) {
            cc.warn(" not have  name ", key, ' ,go.name ', go.name);
            return;
        }
        this.pools[key].put(go,nodePool);
        // cc.log("put -------------------------- 对象池剩余对象数量  ",key,this.pools[key].size());
    }

    clear(name: string) {
        if (this.pools[name]) {
            this.pools[name].clear();
            this.pools[name] = null;
        }
    }
    clealAll() {
        for (const key in this.pools) {
            this.clear(key);
        }
        this.pools = {};
    }
}
